package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //1.通过HttpClient构造请求，发送请求到微信平台，接收响应数据（重点是openid）
        //请求地址：GET + https://api.weixin.qq.com/sns/jscode2session
        //请求参数：appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");
        String jsonResult = HttpClientUtil.doGet(url, paramMap);

        //2.解析响应数据，获取openid，判断该值是否存在
        JSONObject jsonObject = JSON.parseObject(jsonResult);
        String openid = (String) jsonObject.get("openid");
        log.info("openid={}", openid);

        //2.1 如果不存在该值，直接抛出自定义异常（登录失败）
        if (openid == null) {
            throw new UserNotLoginException(MessageConstant.USER_NOT_LOGIN);
        }

        //2.2 如果有值，需要查询数据库user表(根据openid查)
        User user = userMapper.selectByOpenid(openid);

        //3. 判断该用户是否为新用户，如果返回值为空，代表是新用户
        if (user == null) {
            //3.1 需要完成自动注册，往user表中新增一条数据
            user = new User();
            user.setOpenid(openid);
            user.setName("u_"+openid.substring(5,10));  //u_C1ItHg
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }

        //4. 如果返回值不为空，代表该用户之前登录过，直接返回该用户信息
        return user;
    }
}
